package com.itheima.controller;

import com.itheima.entity.PageResult;
import com.itheima.entity.Result;
import com.itheima.service.BlogService;
import com.itheima.vo.BlogVo;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/blog")
@Api(value = "后台管理模块",description = "博客相关接口")
public class BlogController {

    @Autowired
    private BlogService blogService;

    /**
     * 添加博客
     * @param blogVo
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public Result add(@RequestBody BlogVo blogVo){
        try {
            blogService.add(blogVo);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("error","添加失败");
        }

        return new Result("success","添加成功");
        //return "redirect:/blog/getList";
    }

    /**
     * 删除博客
     * @param blogVo
     * @return
     */
    @PostMapping("/delete")
    @ResponseBody
    public Result delete(@RequestBody BlogVo blogVo){
        try {
            blogService.delete(blogVo);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("error","删除失败");
        }

        return new Result("success","删除成功");
        //return "redirect:/blog/getList";
    }

    /**
     * 批量删除选中博客
     * @param blogVoList
     * @return
     */
    @PostMapping("/deleteBatch")
    @ResponseBody
    public Result deleteBatch(@RequestBody List<BlogVo> blogVoList){
        try {
            blogService.deleteBatch(blogVoList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("error","批量删除失败");
        }

        return new Result("success","批量删除成功");
    }

    /**
     * 编辑博客
     * @param blogVo
     * @return
     */
    @PostMapping("/edit")
    @ResponseBody
    public Result edit(@RequestBody BlogVo blogVo){
        try {
            blogService.edit(blogVo);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("error","编辑失败");
        }

        return new Result("success","编辑成功");
        //return "redirect:/blog/getList";
    }

    /**
     * 获取博客列表 根据条件进行分页查询
     * @param blogVo
     * @return
     */
    @PostMapping("/getList")
    @ResponseBody
    public Result getList(@RequestBody BlogVo blogVo ){
        PageResult pageResult = blogService.findAll(blogVo.getKeyword(),blogVo.getCurrentPage(),blogVo.getPageSize());
        return new Result("success",pageResult);
    }
}
